package com.mazong.serversecaa.security;

import com.mazong.serversecaa.service.MyUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    MyUserDetailsService myUserDetailsService;

    //-- 支持自定义密码验证
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    //-- 用户密码验证
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //--1 获取用户输入
        String username = (String)authentication.getPrincipal();
        String password = (String)authentication.getCredentials();
        log.info("username={},password={}", username,password);

        //--2 密码验证
//        if(!username.equals("david") || !password.equals("123456")) {
//            throw new BadCredentialsException("用户名或者密码错误！");
//        }
        UserDetails user = myUserDetailsService.loadUserByUsername(username);
        if(user == null) {
            log.info("authenticate,账号不存在");
            //throw new BadCredentialsException("账号不存在！");
            throw new UsernameNotFoundException("username用户名不可以为空");
        }
        String encode = DigestUtils.md5DigestAsHex(password.getBytes());
        if(!user.getPassword().equals(encode)) {
            log.info("authenticate,密码不正确");
            throw new BadCredentialsException("密码不正确！");
        }

        log.info("用户名和密码都是正确的。。。。");

        //--3 赋值权限
//        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        GrantedAuthority grantedAuthority = new GrantedAuthority() {
//            @Override
//            public String getAuthority() {
//                return "USER";
//            }
//        };
        for(GrantedAuthority grantedAuthority : user.getAuthorities()) {
            log.info("authenticate,role={}", grantedAuthority.getAuthority());
        }

        return new UsernamePasswordAuthenticationToken(username, password, user.getAuthorities());
    }
}
